package com.yyk.dzvisit.interceptor;

import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpRequest;
import org.springframework.http.client.ClientHttpRequestExecution;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.stereotype.Component;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;

/**
 * @Descreption: 服务对外请求日志拦截记录
 * @Date: 2020/6/24 13:11
 * @Author: wxl
 */
@Slf4j
@Component
public class HttpRequestLogInterceptor implements ClientHttpRequestInterceptor {

    @Override
    public ClientHttpResponse intercept(HttpRequest httpRequest, byte[] bytes, ClientHttpRequestExecution clientHttpRequestExecution) throws IOException {
        traceRequest(httpRequest, bytes);
        ClientHttpResponse response = clientHttpRequestExecution.execute(httpRequest, bytes);
        traceResponse(response);
        return response;
    }

    /**
     * <p> 打印请求信息 </p>
     *
     * @param: </br>
     * @return: String </br>
     */
    private void traceRequest(HttpRequest request, byte[] body) {
        // 开发环境直接打印日志
        log.info(" 》》Create {} request: {}", request.getMethod(), request.getURI());
        log.info(" 》》Headers          : {}", request.getHeaders());
        log.info(" 》》Request body     : {}", new String(body, StandardCharsets.UTF_8));
    }

    /**
     * <p> 响应数据 </p>
     *
     * @param: </br>
     * @return: String </br>
     */
    private void traceResponse(ClientHttpResponse response) throws IOException {
        StringBuilder inputStringBuilder = new StringBuilder();
        try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(response.getBody(), StandardCharsets.UTF_8))) {
            String line = bufferedReader.readLine();
            while (line != null) {
                inputStringBuilder.append(line);
                inputStringBuilder.append('\n');
                line = bufferedReader.readLine();
            }
        }
        log.info(" 《《 Response body: {}", inputStringBuilder.toString());
    }
}
